<template>
  <el-dialog
    v-model="dialogVisible"
    :title="dialogTitle"
    width="600px"
    :close-on-click-modal="false"
    append-to-body
  >
    <el-form
      ref="formRef"
      :model="topicForm"
      :rules="rules"
      label-width="100px"
      label-position="right"
    >
      <el-form-item label="名称" prop="name">
        <el-input v-model="topicForm.name" placeholder="请输入名称" />
      </el-form-item>

      <el-form-item label="主题前缀" prop="prefix">
        <el-input v-model="topicForm.prefix" placeholder="请输入主题前缀" />
      </el-form-item>

      <el-form-item label="订阅主题" prop="topic">
        <el-input v-model="topicForm.topic" placeholder="主题名称，例如：sensor/+/temp" />
      </el-form-item>

      <el-form-item label="QoS等级" prop="qos">
        <el-radio-group v-model="topicForm.qos">
          <el-radio-button label="0">QoS 0</el-radio-button>
          <el-radio-button label="1">QoS 1</el-radio-button>
          <el-radio-button label="2">QoS 2</el-radio-button>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="备注">
        <el-input
          v-model="topicForm.remark"
          type="textarea"
          :rows="2"
          placeholder="请输入备注"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleCancel">取 消</el-button>
        <el-button type="primary" @click="handleConfirm" :loading="loading">
          确 定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue';
import type { FormInstance } from 'element-plus';

interface TopicForm {
  name: string;
  prefix: string;
  topic: string;
  qos: '0' | '1' | '2';
  remark: string;
}

const props = defineProps<{
  modelValue: boolean;
  editIndex?: number;
  editData?: Partial<TopicForm>;
  topics?: TopicForm[];
}>();

const emit = defineEmits(['update:modelValue', 'confirm']);

const dialogVisible = computed({
  get: () => props.modelValue,
  set: (val) => emit('update:modelValue', val)
});

const dialogTitle = computed(() => 
  props.editIndex !== undefined ? '编辑主题' : '新增主题'
);

const loading = ref(false);
const formRef = ref<FormInstance>();

const defaultForm: TopicForm = {
  name: '',
  prefix: '',
  topic: '',
  qos: '0',
  remark: ''
};

const topicForm = reactive<TopicForm>({ ...defaultForm });

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入名称', trigger: 'blur' },
    {
      validator: (rule: any, value: string, callback: Function) => {
        if (!value) {
          callback();
          return;
        }
        const exists = props.topics?.some((item, index) => 
          item.name === value && index !== props.editIndex
        );
        if (exists) {
          callback(new Error('名称已存在'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ],
  prefix: [{ required: true, message: '请输入主题前缀', trigger: 'blur' }],
  topic: [
    { required: true, message: '请输入订阅主题', trigger: 'blur' },
    {
      validator: (rule: any, value: string, callback: Function) => {
        if (!value) {
          callback();
          return;
        }
        const exists = props.topics?.some((item, index) => 
          item.topic === value && index !== props.editIndex
        );
        if (exists) {
          callback(new Error('订阅主题已存在'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ],
  qos: [{ required: true, message: '请选择QoS等级', trigger: 'change' }]
};

// 监听编辑数据变化
watch(
  () => props.editData,
  (newVal) => {
    if (newVal) {
      Object.assign(topicForm, { ...defaultForm, ...newVal });
    }
  },
  { immediate: true }
);

// 取消
const handleCancel = () => {
  dialogVisible.value = false;
  formRef.value?.resetFields();
  Object.assign(topicForm, defaultForm);
};

// 确认
const handleConfirm = async () => {
  if (!formRef.value) return;
  
  await formRef.value.validate((valid) => {
    if (valid) {
      loading.value = true;
      try {
        emit('confirm', { ...topicForm }, props.editIndex);
        handleCancel();
      } finally {
        loading.value = false;
      }
    }
  });
};

defineExpose({
  handleCancel
});
</script>

<style scoped>
.el-form-item {
  margin-bottom: 18px;
}

:deep(.el-radio-group) {
  width: 100%;
}

:deep(.el-textarea) {
  width: 100%;
}
</style> 